#include "nfc_spi.h"


static int value = 0x01;

static void dex(void)
{
	int i, j;

	for(i=0; i<100*1; i++){
		for(j=0; j<1000; j++){

		}
	}
}

void spi_loopback(mml_spi_dev_e spi_master, mml_spi_dev_e spi_slave)
{
	unsigned char master_buf[1];
	unsigned char slave_buf[1];
	
	lite_printf("Start test\n");
	/* Initialize first byte of slave transfer to 0x00 */
	slave_buf[0] = 5;
	mml_spi_transmit(spi_slave,slave_buf,1);
	slave_buf[0] = 0;
	
	//while (1)
	{
#if 0	
		/* Slave: Invert last received value and prep to send to master. */
		lite_printf("Slave Send 0x%02X\n",slave_buf[0]);
		mml_spi_transmit(spi_slave,slave_buf,1);
		lite_printf("Slave Recv 0x%02X\n",slave_buf[0]);
		//slave_buf[0] ^= 0xFF;
		slave_buf[0]++;
#endif
		/* Master: Send/receive value to slave. */
		master_buf[0] = value;
		lite_printf("Master Send 0x%02X\n",master_buf[0]);
		mml_spi_transmit(spi_master,master_buf,1);
		lite_printf("Master Recv 0x%02X\n\n",master_buf[0]);
		
		value++;

		dex();
	}
}
	u8 xx  = 3;

static void spi0_test(void)
{
	
	
	
	//while(1){
		xx += 2;
		mml_spi_transmit(MML_SPI_DEV0, &xx,1);
		lite_printf("[SPI] slave_buf =%x\n", xx);
		//dex();
	//}
}

void nfc_spi_trans_test(void)
{
	spi0_test();
	spi_loopback(MML_SPI_DEV0,MML_SPI_DEV2);
}


u8 nfc_spi_init(void)
{
		int											result = COMMON_ERR_UNKNOWN;


	mml_spi_params_t spi_slave = { .baudrate = 1000000,
									.ssel = 1,
									.word_size = 8,
									.mode = MML_SPI_MODE_SLAVE,
									.wor = MML_SPI_WOR_NOT_OPEN_DRAIN,
									.clk_pol = MML_SPI_SCLK_LOW,
									.phase = MML_SPI_PHASE_LOW,
									.brg_irq = MML_SPI_BRG_IRQ_DISABLE,
									.ssv = MML_SPI_SSV_LOW,
									.ssio = MML_SPI_SSIO_INPUT,
									.tlj = MML_SPI_TLJ_DIRECT,
									.dma_tx.active = MML_SPI_DMA_DISABLE,
									.dma_rx.active = MML_SPI_DMA_DISABLE };


		mml_spi_params_t							spi_conf;

	/** Fill parameters */
	spi_conf.baudrate = 1500000;//1500000;
	spi_conf.word_size = 8;
	spi_conf.mode = MML_SPI_MODE_MASTER;
	spi_conf.wor = MML_SPI_WOR_NOT_OPEN_DRAIN;
	spi_conf.clk_pol = MML_SPI_SCLK_LOW;
	spi_conf.phase = MML_SPI_PHASE_LOW;
	spi_conf.brg_irq = MML_SPI_BRG_IRQ_DISABLE;
	spi_conf.ssv = MML_SPI_SSV_LOW;
	spi_conf.ssio = MML_SPI_SSIO_OUTPUT;
	spi_conf.tlj = MML_SPI_TLJ_DIRECT;
	spi_conf.dma_tx.active = MML_SPI_DMA_DISABLE;
	spi_conf.dma_rx.active = MML_SPI_DMA_DISABLE;

		result = mml_spi_init(MML_SPI_DEV0, (mml_spi_params_t*)&spi_conf);
	if ( NO_ERROR == result )
	{
		/** Now enable SPI interface */
		M_MML_SPI_ENABLE(MML_SPI_DEV0);
	}
	
	result = mml_spi_init(MML_SPI_DEV2,&spi_slave);
	if ( NO_ERROR == result)
	{
		M_MML_SPI_ENABLE(MML_SPI_DEV2);
	}

	spi_debug("[SPI] spi init...\n");

	return 0;
}


